<?php
namespace App\Http\Service;
use App\Http\Service\BaseService;
use InvalidArgumentException;

class ContentScoringService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 计算爆料内容的基础分
     */
    public static function calculateReportScore($finalPrice, $userReportPrice, $view_count, $comment_count, $collect_count, $orders)
    {
        if ($finalPrice <= 0) return 0;
        
        $discountStrength = ($finalPrice - $userReportPrice) / $finalPrice;
        
        $popularity = log(
            $view_count * 0.3 + 
            $comment_count * 0.7 + 
            $collect_count * 0.5 + 
            $orders * 1.5 + 
            1
        ) / log(1000);

        return 0.6 * $discountStrength + 0.4 * $popularity;
    }
    /**
     * 计算逛逛内容的热门度
     * @param int $view_count 浏览量
     * @param int $comment_count 评论数
     * @param int $collect_count 收藏数
     * @param int $orders 下单数
     * @return float 热门度
     */
    public static function calculatePopularityScore($view_count,$comment_count,$collect_count,$orders) 
    {
        $popularity = log(
            $view_count * 0.3 + 
            $comment_count * 0.7 + 
            $collect_count * 0.5 + 
            $orders * 1.5 + 
            1
        ) / log(1000);

        return $popularity;
    }


    /**
     * 计算当天热度得分（基于24小时内的互动数据）
     */
    public static function calculateDailyHotScore($content)
    {
        //die("9999");
        //dd($content);
        // 获取当前时间
        $now = time();
        
        // 获取发布时间
        $publishTime = strtotime($content['publish_time'] ?? '1970-01-01');
        
        // 计算发布天数
        $daysSincePublish = max(0, floor(($now - $publishTime) / 86400));
        
        // 基础互动数据（如果没有24小时数据，使用总量并按时间衰减）
        $viewCount = $content['view_count'] ?? 0;
        $commentCount = $content['comment_count'] ?? 0;
        $collectCount = $content['collect_count'] ?? 0;
        $ordersCount = $content['sales_count'] ?? 0;
        
        // 计算时间衰减因子（新内容权重更高）
        $timeDecay = exp(-0.2 * $daysSincePublish);
        
        // 计算当天热度（互动数据 × 时间衰减）
        $hotScore = (
            $viewCount * 0.3 + 
            $commentCount * 0.7 + 
            $collectCount * 0.5 + 
            $ordersCount * 1.5
        ) * $timeDecay;
        
        // 如果是今天发布的内容，额外加成
        $isToday = date('Y-m-d', $publishTime) === date('Y-m-d', $now);
        if ($isToday) {
            $hotScore *= 1.5; // 今天发布的内容热度加成50%
        }
        ///dd($hotScore);
        return $hotScore;
    }
/*
    public static function calculateDailyHotScore($content)
    {
        // 获取当前时间
        $now = time();
        
        // 获取发布时间
        $publishTime = strtotime($content['publish_time'] ?? '1970-01-01');
        
        // 计算发布时间距离当前时间的小时数
        $hoursSincePublish = max(0, floor(($now - $publishTime) / 3600));
        
        // 获取当天浏览量（直接使用view_count字段）
        $viewCount = $content['view_count'] ?? 0;
        
        // 计算每小时浏览量率
        $hourlyViewRate = $hoursSincePublish > 0 ? $viewCount / $hoursSincePublish : $viewCount;
        
        // 估算24小时浏览量（如果发布不足24小时，使用实际数据；如果超过24小时，按比例估算）
        if ($hoursSincePublish <= 24) {
            $estimated24hViews = $viewCount;
        } else {
            $estimated24hViews = $hourlyViewRate * 24;
        }
        
        // 计算时间衰减因子（新内容权重更高）
        // 发布超过24小时的内容会随时间衰减
        $timeDecay = $hoursSincePublish <= 24 ? 1.0 : exp(-0.15 * (($hoursSincePublish - 24) / 24));
        
        // 计算当天热度（估算的24小时浏览量 × 时间衰减）
        $hotScore = $estimated24hViews * $timeDecay;
        
        // 如果是今天发布的内容，额外加成
        $isToday = date('Y-m-d', $publishTime) === date('Y-m-d', $now);
        if ($isToday) {
            $hotScore *= 1.5; // 今天发布的内容热度加成50%
        }
        
        return $hotScore;
    }*/


    /**
     * 对内容列表进行排序
     */
    public static function sortContents($contents, $sortMode = 'comprehensive')
    {
        //dd($sortMode);
        switch ($sortMode) {
            case 'comprehensive': // 综合排序
                usort($contents, function ($a, $b) {
                    $scoreA = self::calculateComprehensiveScore($a);
                    $scoreB = self::calculateComprehensiveScore($b);
                    return $scoreB <=> $scoreA;
                });
                break;

            case 'latest': // 最新
                usort($contents, function ($a, $b) {
                    $timeA = strtotime($a['publish_time'] ?? '1970-01-01');
                    $timeB = strtotime($b['publish_time'] ?? '1970-01-01');
                    return $timeB <=> $timeA;
                });
                break;

            case 'hottest': // 当天最热
   
                //dd($contents);
                usort($contents, function ($a, $b) {
                   // dd($a);
                    $hotScoreA = self::calculateDailyHotScore($a);
                    $hotScoreB = self::calculateDailyHotScore($b);
                    return $hotScoreB <=> $hotScoreA;
                });
                //die("666");
                break;

            case 'high_commission': // 高佣金
                usort($contents, function ($a, $b) {
                    $commissionA = floatval($a['commission_amount'] ?? 0);
                    $commissionB = floatval($b['commission_amount'] ?? 0);
                    return $commissionB <=> $commissionA;
                });
                break;

            case 'high_sales': // 高销量
                usort($contents, function ($a, $b) {
                    $salesA = $a['sales_count'] ?? $a['orders'] ?? 0;
                    $salesB = $b['sales_count'] ?? $b['orders'] ?? 0;
                    return $salesB <=> $salesA;
                });
                break;

            default:
                throw new InvalidArgumentException("Invalid sort mode: {$sortMode}");
        }

        return $contents;
    }

    /**
     * 计算综合得分（用于综合排序）
     */
    private static function calculateComprehensiveScore($content)
    {
        $baseScore = $content['base_score'] ?? 0;
        $publishTime = strtotime($content['publish_time'] ?? '1970-01-01');
        $daysPassed = max(0, floor((time() - $publishTime) / 86400));
        
        // 时间衰减因子
        $timeDecay = exp(-0.1 * $daysPassed);
        
        return $baseScore * $timeDecay;
    }

    /**
     * 获取当天最热内容
     */
    public static function getTodayHottestContents($contents, $limit = 10)
    {
        $todayHottest = [];
        $now = time();
        
        foreach ($contents as $content) {
            $publishTime = strtotime($content['publish_time'] ?? '1970-01-01');
            $daysSincePublish = floor(($now - $publishTime) / 86400);
            
            // 只考虑最近3天内的内容
            if ($daysSincePublish <= 3) {
                $content['daily_hot_score'] = self::calculateDailyHotScore($content);
                $todayHottest[] = $content;
            }
        }
        
        // 按当天热度排序
        usort($todayHottest, function ($a, $b) {
            return $b['daily_hot_score'] <=> $a['daily_hot_score'];
        });
        
        return array_slice($todayHottest, 0, $limit);
    }
}
